<template>
  <q-layout view="lHh Lpr lFf" class="q-login">
    <!-- 头部工具栏 -->
    <q-header elevated>
      <q-toolbar>
        <q-toolbar-title>{{ t('login.title') }}</q-toolbar-title>

        <!-- 语言切换菜单 -->
        <q-btn-dropdown flat color="white" icon="language">
          <q-list>
            <q-item v-for="lang in languageList" :key="lang.code" clickable v-close-popup
                    @click="changeLanguage(lang.code)">
              <q-item-section>
                <q-item-label>{{ lang.label }}</q-item-label>
              </q-item-section>
              <q-item-section side>
                <q-icon name="check" v-if="currentLocale === lang.code" />
              </q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>

        <!-- 用户菜单 -->
        <q-btn-dropdown flat color="f4c521" icon="person" class="user-btn">
          <q-list>
            <q-item clickable v-close-popup @click="checkForUpdates">
              <q-item-section avatar>
                <q-icon name="update" />
              </q-item-section>
              <q-item-section>{{ t('rt.checkUpdates') }} v:{{ getAppVersion() }}</q-item-section>
            </q-item>

            <q-separator />

            <q-item clickable v-close-popup @click="toggleFullscreen">
              <q-item-section avatar>
                <q-icon name="fullscreen" />
              </q-item-section>
              <q-item-section>{{ fullscreenText }}</q-item-section>
            </q-item>

            <q-item clickable v-close-popup @click="refresh">
              <q-item-section avatar>
                <q-icon name="refresh" />
              </q-item-section>
              <q-item-section>{{ t('refresh') }}</q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>
      </q-toolbar>
    </q-header>

    <q-page-container>
      <q-page class="row justify-center bg-grey-2">
        <div class="column items-center justify-center q-card-wrap">

          <q-card class="login-card q-pa-none" style="min-width: 300px; max-width: 90vw;">
            <q-card-section>
              <!-- 登录表单 -->
              <q-form class="q-gutter-md" @submit="handleLogin">
                <!-- RCS2.0服务器地址输入 -->
                <q-input v-model="state.rcs2ServerAddress" :label="t('login.rcs2ServerAddress')" dense
                         @keyup.enter="handleLogin">
                  <template v-slot:prepend>
                    http://
                  </template>
                  <template v-slot:hint>
                    {{ t('login.rcs2Hint') }}
                  </template>
                </q-input>

                <!-- RCS2.0用户名输入 -->
                <q-input v-model="state.rcs2Username" :label="t('login.username')" dense :rules="rcs2UsernameRules"
                         @keyup.enter="handleLogin">
                  <template v-slot:prepend>
                    <q-icon name="person" />
                  </template>
                </q-input>

                <!-- RCS2.0密码输入 -->
                <q-input v-model="state.rcs2Password" :label="t('login.password')" dense type="password"
                         :rules="rcs2PasswordRules" @keyup.enter="handleLogin">
                  <template v-slot:prepend>
                    <q-icon name="lock" />
                  </template>
                </q-input>

                <!-- 作业服务器地址输入

                <q-input v-model="state.projectId" :label="t('login.projectId')" dense :rules="projectIdRules"
                         @keyup.enter="onSubmit">
                  <template v-slot:prepend>
                    <q-icon name="folder"/>
                  </template>
                </q-input>

                <q-input v-model="state.envId" :label="t('login.envId')" dense :rules="envIdRules"
                         @keyup.enter="onSubmit">
                  <template v-slot:prepend>
                    <q-icon name="settings"/>
                  </template>
                </q-input>
                -->

                <!-- 登录按钮 -->
                <q-btn color="primary" icon="login" :label="t('login.loginButton')" :loading="state.loading"
                       type="submit" class="q-mt-md">
                </q-btn>
              </q-form>
            </q-card-section>
          </q-card>

          <!-- RT2 跳转按钮
          <div class="q-mt-md text-center">
            <q-btn color="accent" icon="launch" label="布局测试" @click="goToRT3" class="rt2-btn"/>
          </div>
          <div class="q-mt-md text-center">
            <q-btn color="accent" icon="launch" :label="t('login.rt2Test')" @click="goToRT2" class="rt2-btn"/>
          </div>
          -->
        </div>
      </q-page>
    </q-page-container>

    <!-- 历史登录信息对话框 -->
    <q-dialog v-model="state.showHistoryDialog" persistent>
      <q-card class="history-dialog-card">
        <q-card-section class="history-content">
          <div v-if="state.loginHistory.length === 0" class="text-center q-pa-md">
            <q-icon name="info" size="48px" color="grey-5" />
            <div class="text-grey-6 q-mt-sm">{{ t('login.noHistory') }}</div>
          </div>

          <q-list v-else class="history-list">
            <q-item v-for="(history, index) in state.loginHistory" :key="index" clickable
                    @click="selectHistory(history)" class="history-item">
              <q-item-section avatar>
                <q-icon name="person" color="primary" />
              </q-item-section>
              <q-item-section>
                <q-item-label class="history-username">{{ t('login.username') }}: {{
                    history.username
                  }}
                </q-item-label>
              </q-item-section>
              <q-item-section side>
                <q-btn flat round dense icon="delete" @click.stop="deleteHistory(index)">
                  <q-tooltip>{{ t('login.deleteHistory') }}</q-tooltip>
                </q-btn>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat :label="t('cancel')" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <!-- 版本检查对话框 -->
    <CheckForUpdates v-model="state.showUpdatesDialog" />
  </q-layout>
</template>

<script setup lang="ts">
import { reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import { getAppVersion } from '../utils/version';
import useLoginInfoStore from '../stores/useLoginInfoStore';
import CheckForUpdates from '../components/CheckForUpdates.vue';

const router = useRouter();
const $q = useQuasar();
const { locale, t } = useI18n();
const loginStore = useLoginInfoStore();

// 语言列表配置
interface LanguageOption {
  code: string;
  label: string;
}

const languageList: LanguageOption[] = [
  { code: 'zh-CN', label: '中文' },
  { code: 'en-US', label: 'English' }
];

const currentLocale = computed(() => locale.value);

function changeLanguage(lang: string) {
  locale.value = lang;
}

const state = reactive({
  loading: false,
  showHistoryDialog: false,
  showUpdatesDialog: false,
  loginHistory: [] as LoginInfo[],
  rcs2ServerAddress: '10.10.8.31:8801',
  rcs2Username: 'admin',
  rcs2Password: '123456'
});

// 动态验证规则
const rcs2UsernameRules = computed(() => {
  if (state.rcs2ServerAddress) {
    return [val => !!val || t('login.usernameRequired')];
  }
  return [];
});

const rcs2PasswordRules = computed(() => {
  if (state.rcs2ServerAddress) {
    return [val => !!val || t('login.passwordRequired')];
  }
  return [];
});

// 页面加载时尝试恢复保存的登录信息
onMounted(async () => {
  try {
    // 加载历史登录信息
    state.loginHistory = await loginStore.getLoginHistory();
  } catch (error) {
    console.error(t('login.loadHistoryFailed'), error);
  }
});

// 显示历史登录信息
const showLoginHistory = () => {
  state.showHistoryDialog = true;
};

// 选择历史登录信息
const selectHistory = (history: LoginInfo) => {
  // 根据历史记录类型填充相应字段
  if (history.rcs2ServerUrl) {
    state.rcs2ServerAddress = history.rcs2ServerUrl;
    state.rcs2Username = history.username;
    state.rcs2Password = history.rcs2Password || '';
  }

  state.showHistoryDialog = false;

  LCC.msg(t('login.historySelected'), { type: 'success' });
};

// 删除历史登录信息
const deleteHistory = async (index: number) => {
  try {
    await loginStore.deleteLoginHistory(index);
    state.loginHistory = loginStore.loginHistory;

    LCC.msg(t('login.historyDeleted'), { type: 'success' });
  } catch (error) {
    console.error(t('login.deleteHistoryFailed'), error);
    LCC.msg(t('login.deleteHistoryFailed'), { type: 'error' });
  }
};

// 测试服务器连通性
const testServerConnectivity = async (serverAddress: string): Promise<boolean> => {
  try {
    const url = (serverAddress === '-' ? '/ok' : `http://${serverAddress}/ok`);
    const response = await fetch(url, {
      method: 'GET',
      mode: 'no-cors', // 避免CORS问题
      cache: 'no-cache'
    });
    return true; // 如果能到达这里，说明请求发送成功
  } catch (error) {
    console.error(t('login.testServerFailed', { address: serverAddress }), error);
    return false;
  }
};

// 登录提交处理
const handleLogin = async () => {
  state.loading = true;

  try {
    // 验证RCS2.0相关字段
    if (!state.rcs2ServerAddress || !state.rcs2Username || !state.rcs2Password) {
      throw new Error(t('login.rcs2FieldsRequired'));
    }

    // 如果填写了RCS2.0信息，进行RCS2.0登录
    await performRCS2Login();

  } catch (error: any) {
    const errorMessage = error.message || t('login.loginFailed');
    LCC.showErrorDialog(errorMessage);

  } finally {
    state.loading = false;
  }
};

// 执行RCS2.0登录
const performRCS2Login = async () => {
  // 去掉http://前缀
  const serverAddress = state.rcs2ServerAddress.replace(/^http:\/\//, '');

  try {
    const url = `http://${serverAddress}/auth?username=${state.rcs2Username}&password=${state.rcs2Password}`;
    const response = await LCC.httpGet(url);

    if (response?.IsSuccess) {
      LCC.msg(t('login.loginSuccess'), { type: 'success' });

      const loginInfo: LoginInfo = {
        rcs2ServerUrl: serverAddress,
        username: state.rcs2Username,
        rcs2Password: state.rcs2Password,
        token: response.Data.token
      };

      // 保存登录信息到 store
      loginStore.setLoginInfo(loginInfo);

      // 保存登录历史
      await loginStore.saveLoginHistory(loginInfo);

      // 跳转到RCS2.0页面
      await router.push('/rt/agvList');
    } else {
      const errorMessage = response?.Message?.Msg || t('login.unknownReason');
      throw new Error(t('login.rcs2LoginFailed', { reason: errorMessage }));
    }
  } catch (error: any) {
    throw new Error(t('login.rcs2LoginFailed', { reason: error.message }));
  }
};

function refresh() {
  window.location.reload();
}

// 全屏模式文本
const fullscreenText = computed(() => {
  return $q.fullscreen.isActive ? t('exitFullscreen') : t('fullscreenMode');
});

// 全屏模式切换
function toggleFullscreen() {
  if ($q.fullscreen.isActive) {
    // 退出全屏模式
    $q.fullscreen.exit()
      .then(() => {
        LCC.msg(t('exitedFullscreen'), { type: 'info' });
      })
      .catch(err => {
        // 退出全屏失败
        LCC.msg(t('exitFullscreenFailed') + ': ' + err, { type: 'error' });
      });
  } else {
    // 请求全屏模式
    $q.fullscreen.request()
      .then(() => {
        // 成功进入全屏
        LCC.msg(t('enteredFullscreen', { type: 'info' }));
      })
      .catch(err => {
        // 进入全屏失败
        LCC.msg(t('enterFullscreenFailed') + ': ' + err, { type: 'error' });
      });
  }
}

// 检查更新
async function checkForUpdates() {
  // 显示版本检查对话框
  state.showUpdatesDialog = true;
}

// 跳转到 RT2 页面
const goToRT2 = () => {
  router.push('/rt2');
};

const goToRT3 = () => {
  router.push('/GoldenLayout');
};

</script>

<style lang="less" scoped>
.login-card {
  box-shadow: 0 4px 25px 0 rgba(0, 0, 0, 0.1);
}

/* 确保页面在小屏幕下可以正常滚动 */
:deep(.q-layout) {
  min-height: 100vh;
  overflow: hidden;
}

:deep(.q-page-container) {
  height: calc(100vh - 50px);
  overflow: hidden;
  margin-top: 50px;
}

:deep(.q-page) {
  min-height: 100%;
  overflow: hidden;
}

.q-login {
  .q-page-container {
    padding: 0 !important;
  }
}

/* 历史登录对话框移动端适配 */
.history-dialog-card {
  min-width: 300px;
  max-width: 90vw;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.history-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.history-list {
  max-height: 60vh;
  overflow-y: auto;
}

.history-item {
  border-bottom: 1px solid #f0f0f0;
}

.history-item:last-child {
  border-bottom: none;
}

.history-username {
  font-size: 12px;
  color: #666;
}

/* 超小屏幕适配 */
@media (max-width: 480px) {
  .history-dialog-card {
    min-width: 260px;
    max-width: 98vw;
    max-height: 90vh;
    margin: 4px;
  }

  .history-content {
    padding: 8px;
  }

  .history-list {
    max-height: 45vh;
  }

  .history-url {
    font-size: 12px;
  }

  .history-username {
    font-size: 10px;
  }

  .q-login {
    .q-card-wrap.justify-center {
      justify-content: flex-start;
      padding-top: 30px;
    }
  }
}

/* RT2 按钮样式 */
.rt2-btn {
  min-width: 200px;
  border-radius: 8px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.rt2-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}
</style>
